<template>
  <div class="orders-container">
    <h2>我的订单</h2>
    <el-tabs v-model="activeTab" type="card" class="tabs" @tab-click="onTabClick">
      <el-tab-pane label="全部订单" name="all"></el-tab-pane>
      <el-tab-pane label="待付款" name="unpaid"></el-tab-pane>
      <el-tab-pane label="待发货" name="unshipped"></el-tab-pane>
      <el-tab-pane label="待收货" name="unreceived"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
    </el-tabs>
    <el-card class="box-card">
      <div v-if="filteredOrders.length > 0">
        <div class="order-item" v-for="order in filteredOrders" :key="order.id">
          <div class="order-header">
            <span>订单号: {{ order.orderNo }}</span>
            <el-tag :type="getStatusType(order.status)" size="small">
              {{ getStatusText(order.status) }}
            </el-tag>
          </div>
          <el-table :data="order.orderItems" style="width: 100%">
            <el-table-column label="商品图片" width="80">
              <template #default="scope">
                <img :src="scope.row.productImage" style="width: 60px; height: 60px; object-fit: cover;" />
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="price" label="单价"></el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
            <el-table-column label="小计">
              <template #default="scope">
                {{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="order-footer">
            <div class="order-total">
              总计: <strong>{{ order.totalAmount.toFixed(2) }}</strong>
            </div>
            <div class="order-actions">
              <el-button @click="showOrderDetail(order)">查看详情</el-button>
              <el-button v-if="order.status === 1" type="success" @click="handleConfirmOrder(order.id)">
                付款
              </el-button>
              <el-button v-if="order.status === 1" type="danger" @click="handleCancelOrder(order.id)">
                取消订单
              </el-button>
              <el-button v-if="order.status === 3" type="primary" @click="handleConfirmOrder(order.id)">
                确认收货
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-orders">
        <el-empty description="暂无订单"></el-empty>
      </div>
    </el-card>
    <!-- 订单详情弹窗 -->
    <el-dialog v-model="orderDetailDialogVisible" title="订单详情" width="700px">
      <div v-if="orderDetailLoading" style="text-align:center;padding:40px 0;">
        <el-skeleton :rows="6" animated />
      </div>
      <div v-else-if="orderDetail">
        <div style="margin-bottom: 16px;">
          <strong>订单号：</strong>{{ orderDetail.orderNo }}<br>
          <strong>下单时间：</strong>{{ orderDetail.createTime }}<br>
          <strong>收货人：</strong>{{ orderDetail.receiverName }}<br>
          <strong>联系电话：</strong>{{ orderDetail.receiverPhone }}<br>
          <strong>收货地址：</strong>{{ orderDetail.receiverAddress }}<br>
          <strong>备注：</strong>{{ orderDetail.remark || '-' }}
        </div>
        <el-table :data="orderDetail.orderItems || []" style="width: 100%">
          <el-table-column label="商品图片" width="80">
            <template #default="scope">
              <img :src="scope.row.productImage" style="width: 60px; height: 60px; object-fit: cover;" />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称"></el-table-column>
          <el-table-column prop="price" label="单价"></el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <el-table-column label="小计">
            <template #default="scope">
              {{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 16px; text-align: right;">
          <strong>总计：</strong>{{ orderDetail.totalAmount?.toFixed(2) || '-' }}
        </div>
      </div>
      <div v-else style="text-align:center;padding:40px 0;">
        <el-empty description="暂无订单详情"></el-empty>
      </div>
      <template #footer>
        <el-button @click="orderDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserOrderList, cancelOrder, confirmOrder, getOrderDetailByOrderNo } from '../api/order'
import { ElMessage, ElMessageBox } from 'element-plus'

const activeTab = ref('all')
const orders = ref([])
const filteredOrders = ref([])
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const statusMap = {
  1: { text: '待付款', type: 'warning' },
  2: { text: '已付款', type: 'info' },
  3: { text: '已发货', type: 'info' },
  4: { text: '已完成', type: 'success' },
  5: { text: '已取消', type: 'danger' }
}

function getStatusText(status) {
  return statusMap[status]?.text || '未知状态'
}
function getStatusType(status) {
  return statusMap[status]?.type || 'info'
}

function mapTabToStatus(tab) {
  switch (tab) {
    case 'unpaid': return 1
    case 'unshipped': return 2
    case 'unreceived': return 3
    case 'completed': return 4
    default: return null
  }
}

async function fetchOrders() {
  loading.value = true
  try {
    let status = mapTabToStatus(activeTab.value)
    const params = { pageNum: pageNum.value, pageSize: pageSize.value }
    if (status) params.status = status
    const res = await getUserOrderList(params)
    orders.value = (res.data.list || []).map(order => ({
      id: order.id,
      orderNo: order.orderNo,
      status: order.status,
      createTime: order.createTime,
      totalAmount: order.totalAmount,
      orderItems: (order.items || []).map(item => ({
        productName: item.productName,
        price: item.price,
        quantity: item.quantity,
        productImage: item.productImage
      }))
    }))
    // 补充每个订单的详细商品信息
    for (const order of orders.value) {
      const itemRes = await getOrderDetailByOrderNo(order.orderNo)
      if (itemRes.code === 0 && itemRes.data) {
        order.orderItems = itemRes.data.orderItems || itemRes.data.items || []
      }
    }
    total.value = res.data.total || 0
    filterOrders()
  } catch (e) {
    orders.value = []
    filteredOrders.value = []
  }
  loading.value = false
}

function filterOrders() {
  filteredOrders.value = orders.value
}

function onTabClick() {
  pageNum.value = 1
  fetchOrders()
}

// 订单详情弹窗
const orderDetailDialogVisible = ref(false)
const orderDetailLoading = ref(false)
const orderDetail = ref(null)

async function showOrderDetail(order) {
  orderDetailDialogVisible.value = true
  orderDetailLoading.value = true
  try {
    const res = await getOrderDetailByOrderNo(order.orderNo)
    if (res.code === 0 && res.data) {
      let detail = res.data
      if (!detail.orderItems || !Array.isArray(detail.orderItems)) {
        if (Array.isArray(detail.items)) {
          detail.orderItems = detail.items
        } else {
          detail.orderItems = []
        }
      }
      if ((!detail.orderItems || detail.orderItems.length === 0) && Array.isArray(order.orderItems)) {
        detail.orderItems = order.orderItems
      }
      orderDetail.value = detail
    } else {
      orderDetail.value = null
      ElMessage.error(res.msg || '获取订单详情失败')
    }
  } catch (e) {
    orderDetail.value = null
    ElMessage.error('获取订单详情失败')
  }
  orderDetailLoading.value = false
}

function handleCancelOrder(orderId) {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await cancelOrder(orderId)
      ElMessage.success('订单已取消')
      fetchOrders()
    } catch (e) {}
  })
}

function handleConfirmOrder(orderId) {
  ElMessageBox.confirm('确认已收到货物？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(async () => {
    try {
      await confirmOrder(orderId)
      ElMessage.success('操作成功')
      fetchOrders()
    } catch (e) {}
  })
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}
.tabs {
  margin-bottom: 20px;
}
.order-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}
.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.order-total {
  font-weight: bold;
  margin-top: 10px;
}
.order-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
.empty-orders {
  text-align: center;
  padding: 40px 0;
}
</style>